package com.xianbaovip.consumer.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "defaultFallback")//默认的降级方法
public class ConsumController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/demo")
    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public String test1() {

//        String url="http://localhost:9091/user/demo";
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/demo";

        String url = "http://user-service/user/demo";



        String forObject = restTemplate.getForObject(url, String.class);

        return forObject;
    }
    public String queryByIdFallback() {
        return "降级处理";
    }


    public String defaultFallback() {
        return "默认降级处理";
    }
}
